<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <!-- 引入样式 -->
    <link rel="stylesheet" href="../../plugins/element-ui/index.css"/>
    <link rel="stylesheet" href="../../styles/common.css"/>
    <link rel="stylesheet" href="../../styles/page.css"/>
    <style>
        #member-app .notAdmin::after {
            border: 0 !important;

        }
    </style>
</head>
<body>
<div class="dashboard-container" id="member-app">
    <div class="container">
        <div class="tableBar">
            <el-input
                    v-model="input"
                    placeholder="请输入员工姓名"
                    style="width: 250px"
                    clearable
                    @keyup.enter.native="handleQuery"
            >
                <i
                        slot="prefix"
                        class="el-input__icon el-icon-search"
                        style="cursor: pointer"
                        @click="handleQuery"
                ></i>
            </el-input>
            <el-button
                    type="primary"
                    @click="addMemberHandle('add')"
            >
                + 添加员工
            </el-button>

            <el-input
                    placeholder="请输入文件名称内容"
                    v-model="inputFile" style="width: 250px"
                    clearable>
            </el-input>
            <el-button type="primary"
                       @click="downloadWord()">下载
                <i class="el-icon-folder-opened el-icon--right"></i>
                <!-- <p>
                   下载进度:{{downLoadProgress}}
                 </p>-->
            </el-button>
            <!-- <el-input
                     placeholder="请输入文件名称内容"
                     v-model="inputFile" style="width: 250px"
                     clearable>
             </el-input>-->
            <!-- <el-button type="file"
                        @click="uploadWord()">下载
               <i class="el-icon-upload el-icon&#45;&#45;right"></i>
             </el-button>-->
        </div>
        <div>
            <input type="file" @change="uploadWord">上传
            <i class="el-icon-upload el-icon--right"></i>
            </button>

            <p>
                上传进度:0
            </p>

        </div>
        <div>
            <el-upload
                    class="upload-demo"
                    action="/common/upload"
                    multiple
                    ref="upload"
                    :on-preview="handlePreview"
                    :on-remove="handleRemove"
                    list-type="picture"
            >
                <el-button size="small" type="primary">点击上传</el-button>
                <!--<div slot="tip" class="el-upload__tip">只能上传jpg/png文件，且不超过500kb</div>-->
            </el-upload>
        </div>
        <h4>单独上传 不自动保存</h4>
        <div>
            <el-upload class="upload"
                       ref="upload"
                       action="string"
                       :file-list="fileList"
                       :auto-upload="false"
                       :http-request="uploadFileTest"
                       :before-upload="beforeUploadTest"
                       :on-change="handleChangeTest"
                       :on-preview="handlePreviewTest"
                       :on-remove="handleRemoveTest"
                       multiple="multiple"
                       list-type="picture"
            >
                <el-button slot="trigger"
                           size="small"
                           type="primary"
                           @click="delFile">选取文件
                    <i class="el-icon-upload"></i>
                </el-button>
                <el-button type="primary" @click="SaveFile">保存</el-button>
            </el-upload>
            <el-progress :stroke-width="16" :percentage="progressPercent"></el-progress>
            <!--    准备一个提交按钮-->
            <!--            <el-button type="primary"-->
            <!--                       @click="onSubmit">保存-->
            <!--            </el-button>-->
            <!--            <el-button type="primary"  @click="SaveFile">保存</el-button>-->
        </div>
        <el-table
                :data="tableData"
                stripe
                class="tableBox"
        >
            <el-table-column
                    prop="name"
                    label="员工姓名"
            ></el-table-column>
            <el-table-column
                    prop="username"
                    label="账号"
            ></el-table-column>
            <el-table-column
                    prop="phone"
                    label="手机号"
            ></el-table-column>
            <el-table-column label="账号状态">
                <template slot-scope="scope">
                    {{ String(scope.row.status) === '0' ? '已禁用' : '正常' }}
                </template>
            </el-table-column>
            <el-table-column
                    label="操作"
                    width="160"
                    align="center"
            >
                <template slot-scope="scope">
                    <el-button
                            type="text"
                            size="small"
                            class="blueBug"
                            @click="addMemberHandle(scope.row.id)"
                            :class="{notAdmin:user !== 'admin'}"
                    >
                        编辑
                    </el-button>
                    <el-button
                            type="text"
                            size="small"
                            class="delBut non"
                            @click="statusHandle(scope.row)"
                            v-if="user === 'admin'"
                    >
                        {{ scope.row.status == '1' ? '禁用' : '启用' }}
                    </el-button>
                </template>
            </el-table-column>
        </el-table>
        <el-pagination
                class="pageList"
                :page-sizes="[10, 20, 30, 40]"
                :page-size="pageSize"
                layout="total, sizes, prev, pager, next, jumper"
                :total="counts"
                :current-page.sync="page"
                @size-change="handleSizeChange"
                @current-change="handleCurrentChange"
        ></el-pagination>
    </div>
</div>
<!-- 开发环境版本，包含了有帮助的命令行警告 -->
<script src="../../plugins/vue/vue.js"></script>
<!-- 引入组件库 -->
<script src="../../plugins/element-ui/index.js"></script>
<!-- 引入axios -->
<script src="../../plugins/axios/axios.min.js"></script>
<script src="../../js/request.js"></script>
<script src="../../api/member.js"></script>
<script>
    new Vue({
        el: '#member-app',
        data() {
            return {
                input: '',
                inputFile: '',
                downLoadProgress: 0,
                counts: 0,
                page: 1,
                pageSize: 10,
                tableData: [],
                id: '',
                status: '',
                // el-upload组件绑定的属性—— :file-list=“fileList”,渲染后fileList[index]是Object类型,而不是后台所需的File类型,
                // 而这个组件已经把对应的File类型存储到了fileList[index].raw这个属性里,直接拿来用就好.
                fileList: [],//存放选择的文件
                // 不支持多选
                multiple: false,
                formData: '',
                buildUploadUrl: '',
                fileNameUploadTest: '',
                progressPercent:0,
            }
        },
        computed: {},
        created() {
            this.init()
            this.user = JSON.parse(localStorage.getItem('userInfo')).username
        },
        mounted() {
        },
        methods: {
            async init() {
                const params = {
                    page: this.page,
                    pageSize: this.pageSize,
                    name: this.input ? this.input : undefined
                }
                await getMemberList(params).then(res => {
                    if (String(res.code) === '1') {
                        this.tableData = res.data.records || []
                        this.counts = res.data.total
                    }
                }).catch(err => {
                    this.$message.error('请求出错了：' + err)
                })
            },
            handleQuery() {
                this.page = 1;
                this.init();
            },
            // 添加
            addMemberHandle(st) {
                if (st === 'add') {
                    window.parent.menuHandle({
                        id: '2',
                        url: '/backend/page/member/add.html',
                        name: '添加员工'
                    }, true)
                } else {
                    window.parent.menuHandle({
                        id: '2',
                        url: '/backend/page/member/add.html?id=' + st,
                        name: '修改员工'
                    }, true)
                }
            },
            downloadWord() {
                //debugger;
                console.log(this.inputFile)
                console.log(this.inputFile.length)
                console.log(this.inputFile.indexOf("."))
                if (this.inputFile === undefined) {
                    return this.$message.error('请输入正确文件名称' + this.inputFile)
                }
                if (this.inputFile.length < 1 || this.inputFile === null || this.inputFile.indexOf(".") == -1) {
                    return this.$message.error('请输入正确文件名称' + this.inputFile)
                }
                let webFileName = this.inputFile;
                // axios.post('/common/downloadFile?name=0a3b3288-3446-4420-bbff-f263d0c02d8e.jpg').then(
                //         response => (
                //                 // this.info = response.data,
                //                 console.log(response),
                //                   this.$message.success('下载成功！')
                //         )
                // );
                const url = '/common/downloadFile?name=' + webFileName;
                // axios.get(url, {
                //   // params: {},
                //   // headers: {
                //   //   caid: caId,
                //   //   tissueid: tissueId,
                //   //   token: token,
                //   //   username: username,
                //   // },
                //   responseType: 'blob', // 切记类型 blob
                // }).then((response) => {
                //   console.log(response);
                //   const url = window.URL.createObjectURL(new Blob([response.data]));
                //   const link = document.createElement('a');
                //   link.href = url;
                //   link.setAttribute('download', '0a3b3288-3446-4420-bbff-f263d0c02d8e.jpg');
                //   document.body.appendChild(link);
                //   link.click();
                //   window.URL.revokeObjectURL(url); // 释放该 url
                // }).catch((err) => {
                //   this.$message.error('请求出错了：' + err)
                // })
                // let downLoadProgress=0;
                axios.get(url, {
                    // params: {},
                    // headers: {
                    //   caid: caId,
                    //   tissueid: tissueId,
                    //   token: token,
                    //   username: username,
                    // },
                    responseType: 'blob', // 切记类型 blob
                    // onDownloadProgress 配置该属性代表允许为下载处理进度事件
                    onDownloadProgress: function (progressEvent) {//axios封装的原生获取下载进度的事件，该回调参数progressEvent中包含下载文件的总进度以及当前进度
                        debugger;
                        if (progressEvent.lengthComputable) {
                            //属性lengthComputable主要表明总共需要完成的工作量和已经完成的工作是否可以被测量
                            //如果lengthComputable为false，就获取不到progressEvent.total和progressEvent.loaded
                            downLoadProgress = progressEvent.loaded / progressEvent.total * 100 //实时获取最新下载进度
                            console.log(downLoadProgress);
                        }
                    },
                }).then((response) => {
                    console.log(response);
                    const {data, headers} = response
                    let fileName
                    if (headers['content-disposition']) {
                        fileName = headers['content-disposition'].replace(/\w+;filename=(.*)/, '$1')
                    } else {
                        fileName = data.fileName
                    }
                    console.log(fileName)
                    const urldata = window.URL.createObjectURL(new Blob([response.data]));
                    const link = document.createElement('a');
                    link.href = urldata;
                    link.setAttribute('download', decodeURI(fileName));
                    document.body.appendChild(link);
                    link.click();
                    window.URL.revokeObjectURL(urldata); // 释放该 url
                    this.$message.success('下载成功！')
                }).catch((err) => {
                    this.$message.error('请求出错了：' + err)
                })
            },
            //上传
            uploadWord() {
                this.$message.success('上传成功！')
            },
            /*
                response 直接请求方式
             */
            // handleRemove(file) {
            //     debugger;
            //     console.log(file);
            //     console.log("移除" + file.response.data);
            //     axios.delete('/common/deleteFile', {
            //         params: {name: file.response.data},
            //         // data:{name:file.response.data}
            //     }).then(
            //         //(request,response)
            //         (res) => {
            //             // console.log(' 请求-name'+request.params.name);
            //             // console.log(' 请求'+JSON.stringify(request));
            //             debugger;
            //             console.log(' 响应' + JSON.stringify(res));
            //             if (res.data.code === 1) {
            //                 this.info = res.data;
            //                 this.$message.success("成功:" + res.data)
            //             } else {
            //                 this.$message.error(res.msg || '操作失败')
            //             }
            //         }).catch((err) => {
            //         this.$message.error('请求出错了：' + err)
            //     });
            //     // axios.delete('/common/deleteFile',file.response.data
            //     // ).then(
            //     //         response =>
            //     //                 (this.info = response.data))
            //     //         .catch((err) => {
            //     //   this.$message.error('请求出错了：' + err)
            //     // });
            // },
            handleRemove(file) {
                debugger;
                console.log(file);
                console.log("移除" + file.response.data);
                commonDeleteFile(file.response.data).then(
                    //(request,response)
                    (res) => {
                        // console.log(' 请求-name'+request.params.name);
                        // console.log(' 请求'+JSON.stringify(request));
                        // debugger;
                        console.log(' 响应' + JSON.stringify(res));
                        if (res.code === 1) {
                            this.info = res.data;
                            this.$message.success("成功:" + res.data)
                        } else {
                            this.$message.error(res.msg || '操作失败')
                        }
                    }).catch((err) => {
                    this.$message.error('请求出错了：' + err)
                });
                // axios.delete('/common/deleteFile',file.response.data
                // ).then(
                //         response =>
                //                 (this.info = response.data))
                //         .catch((err) => {
                //   this.$message.error('请求出错了：' + err)
                // });
            },
            handlePreview(file) {
                console.log(file);
            },
            //上传不保存
            // :http-request="uploadFileTest"
            //:on-change="handleChangeTest"
            //:on-preview="handlePreviewTest"
            //:on-remove="handleRemoveTest"
            // :file-list="fileList"	//存放选择的文件
            //:auto-upload="false"	//取消自动上传
            //自定义上传的方法
            //上传前对文件大小进行校验
            beforeUploadTest(file) {
                console.log(' beforeUploadTest 响应 file' + file.size);
                const isLt2M = file.size / 1024 / 1024 < 50;
                if (!isLt2M) {
                    this.$message.error('上传文件大小大小不能超过 50MB!');
                    return isLt2M;
                }
            },
            uploadFileTest(file, fileList) {
                this.formData.append("file", file.file);
                console.log("自定义上传的方法_uploadFileTest" + file + ";" + fileList);

            },
            handleRequest (data) {
                let formdata = new FormData()
                formdata.append('file', data.file)
                const config = {
                    onUploadProgress: progressEvent => {
                        // progressEvent.loaded:已上传文件大小
                        // progressEvent.total:被上传文件的总大小
                        this.progressPercent = Number((progressEvent.loaded / progressEvent.total * 100).toFixed(2))
                    }
                }
                this.$axios.post(this.actionURL,formdata,config).then(res => {
                    if (res.data.code===1) {}
                })
            },
            //文件选择后执行的方法
            handleChangeTest(file, fileList) {
                this.fileList = fileList;
                console.log(' 文件选择后执行的方法 handleChangeTest' + JSON.stringify(file));
                console.log("文件选择后执行的方法_handleChangeTest" + file.name);
                console.log("文件选择后执行的方法_handleChangeTest" + file);
                // this.fileNameUploadTest=file.name;
                // this.fileList.add(file)
                // this.formData.append("file", file);
                // 数据小于0.1M的时候按KB显示
                const size = file.size/1024/1024 > 0.1 ? `(${(file.size/1024/1024).toFixed(1)}M)` : `(${(file.size/1024).toFixed(1)}KB)`
                file.name.indexOf('M')>-1 || file.name.indexOf('KB')>-1 ? file.name : file.name += size
            },
            //点击显示文件（没啥用）
            handlePreviewTest(file) {
                console.log("点击显示文件handlePreviewTest（" + file);
            },
            //移除文件
            handleRemoveTest(file, fileList) {
                console.log(file, fileList);
                console.log("移除文件_handleRemoveTest" + file);
                console.log("移除文件_handleRemoveTest" + JSON.stringify(file));
                console.log("移除文件_handleRemoveTest_新名称" + JSON.stringify(this.fileNameUploadTest));
                if (this.fileNameUploadTest.length<1 ||this.fileNameUploadTest===null || this.fileNameUploadTest===undefined) {
                    this.progressPercent=0;
                    return this.$message.success("移除成功!")
                }
                commonDeleteFile(this.fileNameUploadTest).then(
                    //(request,response)
                    (res) => {
                        // console.log(' 请求-name'+request.params.name);
                        // console.log(' 请求'+JSON.stringify(request));
                        // debugger;
                        console.log(' 响应' + JSON.stringify(res));
                        if (res.code === 1) {
                            this.fileNameUploadTest='';
                            this.progressPercent=0;
                            this.$message.success("成功:" + res.data)
                        } else {
                            this.$message.error(res.msg || '操作失败')
                        }
                    }).catch((err) => {
                    this.$message.error('请求出错了：' + err)
                });
            },
            //点击上传文件触发的额外事件,清空fileList
            delFile() {
                this.fileList = [];
                console.log("delFile" + this.fileList);
            },
            //保存按钮
            SaveFile() {
                // this.$message.success("SaveFile 成功:")
                let formDataUpload = new FormData();
                console.log("SaveFile" + this.fileList.length);
                console.log("this.fileList[0].raw" + this.fileList[0].raw);
                this.$message.success("this.fileList[0].raw 成功:" + this.fileList[0].raw)
                formDataUpload.append("file", this.fileList[0].raw);//拿到存在fileList的文件存放到formData中
                //下面数据是我自己设置的数据,可自行添加数据到formData(使用键值对方式存储)
                // formDataUpload.append("title", this.title);
                //注意：使用FormData提交文件只能使用post请求
                //在post请求体中需要设置 “Content-Type”:
                //“multipart/form-data;charset=utf-8”,提醒后台数据是FormData类型
                const config = {
                    onUploadProgress: progressEvent => {
                        // progressEvent.loaded:已上传文件大小
                        // progressEvent.total:被上传文件的总大小
                        this.progressPercent = Number((progressEvent.loaded / progressEvent.total * 100).toFixed(2))
                    }
                }
                // axios.post("/common/saveUpload", formDataUpload, {
                axios.post("/common/saveUpload", formDataUpload,config, {
                    "Content-Type": "multipart/form-data;charset=utf-8"
                })
                    .then(res => {
                        console.log(' 响应 res' + JSON.stringify(res));
                        if (res.data.code === 1) {
                            this.fileNameUploadTest = res.data.data;
                            this.info = res.data.data;
                            console.log('this.fileNameUploadTest 上传成功后:'+this.fileNameUploadTest)
                            this.$notify({
                                title: '成功',
                                message: '提交成功' + this.info,
                                type: 'success',
                                duration: 3000
                            });
                        } else {
                            this.$message.error(res.data.msg || '操作失败')
                        }
                    }).catch((err) => {
                    this.$message.error('请求出错了：' + err)
                })


            },
            //状态修改
            statusHandle(row) {
                this.id = row.id
                this.status = row.status
                this.$confirm('确认调整该账号的状态?', '提示', {
                    'confirmButtonText': '确定',
                    'cancelButtonText': '取消',
                    'type': 'warning'
                }).then(() => {
                    enableOrDisableEmployee({'id': this.id, 'status': !this.status ? 1 : 0}).then(res => {
                        console.log('enableOrDisableEmployee', res)
                        console.log(' 响应' + JSON.stringify(res));
                        if (String(res.code) === '1') {
                            this.$message.success('账号状态更改成功！')
                            this.handleQuery()
                        }
                    }).catch(err => {
                        this.$message.error('请求出错了：' + err)
                    })
                })
            },
            handleSizeChange(val) {
                this.pageSize = val
                this.init()
            },
            handleCurrentChange(val) {
                this.page = val
                this.init()
            }
        }
    })
</script>
</body>
</html>
